package com.atguigu.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.srb.oss.service.OssService;
import com.atguigu.srb.oss.util.OssProperties;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadImage(MultipartFile multipartFile, String module) {
        OSS oss = new OSSClientBuilder().build(
                OssProperties.END_POINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );

        String fileName = UUID.randomUUID().toString();
        // 获取文件名
        String originalFilename = multipartFile.getOriginalFilename();
        // 获取文件后缀
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        try {
            oss.putObject(OssProperties.BUCKET_NAME, module + "/" + fileName + "." + filenameExtension, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回图片访问url,将来提表单存储数据库
        String url = "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.END_POINT + "/" + module + "/" + fileName + "." + filenameExtension;
        oss.shutdown();
        return url;
    }

    @Override
    public void removeImage(String url) {
        OSS oss = new OSSClientBuilder().build(
                OssProperties.END_POINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET
        );
        String subUrl = url.substring(("https://" + OssProperties.BUCKET_NAME + "." + OssProperties.END_POINT + "/").length());
        oss.deleteObject(OssProperties.BUCKET_NAME,subUrl);
        oss.shutdown();
    }
}
